package word;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.heavenlake.wordapi.Document;

public class WordDAO {
	

	public void exportTable(String docFile,String[] title,ArrayList<String[]> tableData,String tableStyle) {
		Document doc = null;
		try {
			doc = new Document();
			doc.newDoc(docFile);
			
			if(tableStyle!=null&&!"".equals(tableStyle)){
				doc.insert(tableData,tableStyle);
			}
			else{
				doc.insert(tableData);
			}
		}
	    catch (Exception e) {
	     	e.printStackTrace();
	    }
	    finally {
	    	try {
	    		if(doc!=null) doc.close(true);
	    	}
	    	catch (Exception e) {
	    		e.printStackTrace();
	    	}
	    }
	}
	
	public int applyToCopyWord(String docFile,Map<String,?> data,String copyFile) {
		return applyToCopyWord(docFile,data,null,copyFile);
	}
	
	public int applyToCopyWord(String docFile,Map<String,?> data,Map<Integer,List<String[]>> listData,String copyFile) {
		try {
			org.apache.commons.io.FileUtils.copyFile(new File(docFile), new File(copyFile));
			return applyToWord(copyFile,data,listData);
		} catch (IOException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public int applyToWord(String docFile,Map<String,?> data) {
		return applyToWord(docFile,data,null);
	}
	
	public int applyToWord(String docFile,Map<String,?> data,Map<Integer,List<String[]>> listData) {
		Document doc = null;
		try {
			
			doc = new Document();
			doc.open(docFile);
			for(String bookmark : data.keySet()){
				Object o = data.get(bookmark);
				if(o instanceof String){
					doc.insertAtBookmark(bookmark, (String)data.get(bookmark));
				}
				else if(o instanceof File){
					doc.insertAtBookmark(bookmark, (File)data.get(bookmark));
				}
				else if(o instanceof List){
					try{
						doc.insertAtBookmark(bookmark, (List)data.get(bookmark),"");
					}
					catch(Exception e){
						continue;
					}
					
				}
			}
			if(listData!=null){
				Iterator<Integer> iterator = listData.keySet().iterator();
				while(iterator.hasNext()){
					Integer tbIndex = iterator.next();
					doc.replaceTable(tbIndex, 1, 1 , listData.get(tbIndex));
				}
			}
			
			return 1;
		} catch (Exception e) {

			return -1;
		} finally {
			try {
				if (doc != null)
					doc.close(true);
			} catch (Exception e) {
				
				return -1;
			}
		}
	}
}
